<?

/**
 * Parse and execute annotations like this:
 * @validate this->validate(email)
 * @validate EmailValidator
 * ***************************************
 */
class ValidateAnnotation extends Annotation {
	
	
	protected $className;
	protected $methodName;
	protected $parameters=array();
	
	public function execute($val) {
		if($this->className=='this') {
			$method=$this->reflectionClass->getMethod($this->methodName);
			array_unshift($this->parameters,$val);
			return $method->invokeArgs($this->actionInstance,$this->parameters);
		} else {
			if(class_exists($this->className)) {
				$class = new ReflectionClass ( $this->className );
				$this->actionInstance=$class->newInstance();
				$method=$class->getMethod($this->methodName);
				array_unshift($this->parameters,$val);
				return $method->invokeArgs($this->actionInstance,$this->parameters);
			} else 
				throw new ValidatorInvokeException ( 'Validation class is not found<b>' . $this->className . '</b>!' );
		}
		
	}
	
	protected function parseAnno() {
		$classAndMethod=$this->getClassAndMethod($this->anno);
		$methodWithParameters=$this->getMethodWithParameters($classAndMethod[1]);
		if(isset($methodWithParameters[1])) { // if has parameters
			$this->parameters=$methodWithParameters[1];
		}
		$this->methodName=strtolower(trim($methodWithParameters[0]));
		$this->className=strtolower(trim($classAndMethod[0]));
	}
	
	protected function getMethodWithParameters($str) {
		$matches = array();
		$ret=array();
		preg_match('/(.*)\((.*)\)/', $str, $matches);
		if (isset($matches[1]))
			$ret[0]=trim($matches[1]);
		else
			$ret[0]=trim($str);
		if (isset($matches[2]))
			$ret[1]=split(',',trim($matches[2]));
		return $ret;
	}

	protected function getClassAndMethod($str) {
		$matches = array();
		$ret=array();
		preg_match('/(.*)->(.*)/', $str, $matches);
		if (isset($matches[1]))
			$ret[0]=trim($matches[1]);
		else
			$ret[0]=trim($str);
		if (isset($matches[2]))
			$ret[1]=trim($matches[2]);
		else
			$ret[1]='validate';
		return $ret;
	}
	  
	
}
?>